import useUserStore from '@/store/user.js'
import requestCanceler from './requestCancel.js'
import { http, toast} from '@/uni_modules/uview-plus'
const requestInterceptors = (vm) => {
	/**
	 * 请求拦截
	 * @param {Object} http
	 */
	http.interceptors.request.use(async (config) => {
		
			// const userStore = useUserStore()
			// config.header.type = userStore.type || 'mini'
			// config.header.Authorization = 'bearer '+ userStore.token || ''
			// console.log('config', config)
			await requestCanceler.addPending(config)
			return config
		}, (config) =>
		Promise.reject(config))
}

const responseInterceptors = (vm) => {
	http.interceptors.response.use((response) => {
		const userStore = useUserStore()
		requestCanceler.removePending(response.config)
		let data = response.data
		if(data.code !==0){
		 uni.showModal({
			title: '提示',
			content: data.msg || '请求失败',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
				}
			}
		})
		 return Promise.reject(data)
		}
		if (data.code == '250') {
			if (userStore.token) {
				let pages = getCurrentPages();
				//获取当前页面
				let currentPage = pages[pages.length - 1].route;
				//如果当前处于首页，则...
				if (currentPage != 'pages/index/index') {
					// this.getTaskInfo();
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
				uni.showToast({
					icon: "error",
					title: "登录异常，请重新登录"
				})
				userStore.setLoginInfo({})
				userStore.setUser(null)
				return Promise.reject('账号异常')
			} else {
				return data
			}
		}

		return data
	}, (error) => {
		const userStore = useUserStore()
		requestCanceler.removePending(error.config)
		// 自定义回调
		const custom = error.config?.custom
		if (custom?.catch) {
			return Promise.reject(error)
		} else if (error?.data?.msg || error?.data?.message) {
			uni.$u.toast(error.data?.msg || error.data?.message)
		} else if (error?.errMsg === 'request:fail abort') {
			return Promise.reject(error)
		}
		return Promise.reject(error)
	})
}

//  初始化请求配置
const initRequest = (vm) => {
	http.setConfig((defaultConfig) => {
		/* defaultConfig 为默认全局配置 */
		defaultConfig.baseURL = import.meta.env.VITE_API_URL /* 根域名 */
		defaultConfig.dataType = 'string'
		return defaultConfig
	})
	requestInterceptors()
	responseInterceptors()
}
export {
	initRequest
}